<template>
  <div>
    <el-form ref="form" :model="formBuffer"  :rules="rulesValue">
      <el-form-item :label-width="labelWidth" v-for="(item, index) in formValue" :label="item.value" :prop="item.key" :key="index">
        <el-input v-if="item.type === 'text'" v-model="item.data" @change="checkformValue" :placeholder="'请输入' + item.value"></el-input>
        <el-input v-if="item.type === 'password'" v-model="item.data" @change="checkformValue" :placeholder="'请输入' + item.value" show-password></el-input>
      </el-form-item>

      <slot name="formAdd">
      </slot>

      <slot name="btnControl">
      </slot>
    </el-form>

  </div>
</template>

<script>

const rules = {}

export default {
  data () {
    return {
      rulesValue: _.cloneDeep(rules),
      formBuffer: {}
    }
  },
  props: {
    formValue: {
      type: Array,
      // 对象或数组默认值必须从一个工厂函数获取
      default: function () {
        return []
      }
    },
    labelWidth: {
      type: String,
      default: '100px'
    }
  },
  created () {
    this.getRulesValue()
  },
  mounted () {

  },
  methods: {

    checkformValue () {
      let formValue = this.formValue
      let formBuffer = {}
      formValue.forEach(item => {
        formBuffer[item.key] = item.data
      })
      this.formBuffer = formBuffer
    },

    getRulesValue () {
      let newRules = {}
      let formList = this.formValue
      let formBuffer = {}
      if (formList && formList.length > 0 && typeof (formList) !== 'undefined') {
        formList.forEach(item => {
          if (item.required) {
            newRules[item.key] = [
              { required: true, message: `请输入正确的${item.value}`, trigger: 'blur' },
              { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }
            ]
          }
          formBuffer[item.key] = item.data
        })
      }
      this.formBuffer = formBuffer
      this.rulesValue = newRules
    }
  },
  watch: {
  }
}
</script>
